/*
 Copyright 2007 Ole Rogeberg

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package org.lifeyears.web.resulttype;

import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.dispatcher.ServletActionRedirectResult;
import org.lifeyears.web.action.AbstractLifeyearsAction;
import org.lifeyears.web.interceptor.ExtractMessagesInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;

/**
 * Struts result which prior to a redirect puts errors, fieldErrors, messages, parameters in session
 * for ExtractMessagesInterceptor to extract later.
 *
 * Per default, errors and fieldErrors and messages are put in session. Parameters are per default
 * put in session iff the result code of the action was Action.ERROR. This behavior may be
 * overridden by setting the boolean fields "errors", "fieldErrors", "messages" and "parameters".
 *
 * @see ExtractMessagesInterceptor
 *
 * @author Aleksander Blomskøld
 *
 */
public class RedirectAndKeepMessagesResult
    extends ServletActionRedirectResult
{
    public static final String SESSION_KEY_START = "RedirectAndKeepMessages_";

    private final Logger log = LoggerFactory.getLogger( getClass() );

    // fields which specifies whether these should be put in session
    private Boolean errors, fieldErrors, messages, parameters;

    protected final Map<String, String> requestParameters = new HashMap<String, String>();

    @Override
    public void execute( final ActionInvocation invocation )
        throws Exception
    {

        final ActionContext actionContext = invocation.getInvocationContext();

        // Get the action
        final Object action = invocation.getAction();

        if ( action instanceof AbstractLifeyearsAction )
        {

            final AbstractLifeyearsAction abstractLifeyearsAction = (AbstractLifeyearsAction) action;
            // first, store away vars
            final ResultValue resultValue = new ResultValue();
            if ( errors == null || errors == Boolean.TRUE )
            {
                resultValue.setErrors( abstractLifeyearsAction.getActionErrors() );
            }
            if ( messages == null || messages == Boolean.TRUE )
            {
                resultValue.setMessages( abstractLifeyearsAction.getActionMessages() );
            }
            if ( fieldErrors == null || fieldErrors == Boolean.TRUE )
            {
                resultValue.setFieldErrors( abstractLifeyearsAction.getFieldErrors() );
            }
            // default for parameters is true iff the result code was "error"
            if ( (parameters == null && invocation.getResultCode().equals( Action.ERROR )) || parameters == Boolean.TRUE )
            {
                resultValue.setParameters( actionContext.getParameters() );
            }

            // put them in the session
            // ExtractMessagesInterceptor will extract them later
            actionContext.getSession().put( getSessionKey( actionName ), resultValue );

        }
        else
        {
            log.warn( "Action not an AbstractLifeyearsAction: {} ", action );
        }

        // execute the redirect
        super.execute( invocation );
    }

    public static String getSessionKey( final String actionName )
    {
        return SESSION_KEY_START + actionName;
    }

    public void setErrors( final boolean errors )
    {
        this.errors = errors;
    }

    public void setFieldErrors( final boolean fieldErrors )
    {
        this.fieldErrors = fieldErrors;
    }

    public void setMessages( final boolean messages )
    {
        this.messages = messages;
    }

    public void setParameters( final boolean parameters )
    {
        this.parameters = parameters;
    }
}
